package dk.mga.androidExplore.sensor;

import java.util.ArrayList;
import java.util.Iterator;


import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class SensorReader implements SensorEventListener {

	private ArrayList<ISensorListener> listeners;
	private SensorManager sm;
	private Sensor sensor;
	private SensorEventListener eventListener;
	private int sensorID;
	private final String tag = "myLog";
	private long startTime;
	
	public SensorReader(SensorManager sm, int sensorID) {
		this.sm = sm;
		this.sensorID = sensorID;
		sensor = this.sm.getDefaultSensor(sensorID);
		listeners = new ArrayList<ISensorListener>();
	    this.eventListener = new SensorEventListener() {
			  
		    public void onSensorChanged(SensorEvent event) {
				  Log.i(tag, "Sensor name: "+event.sensor.getName());
				  if (event.sensor.getType()==SensorReader.this.sensorID) {
					  Iterator<ISensorListener> i = listeners.iterator();
					  while (i.hasNext()){
						  ISensorListener sl = i.next();
						  int scale = sl.getResolutionY();
						  if (SensorReader.this.sensorID == Sensor.TYPE_ACCELEROMETER) {
							  sl.setValues((int)event.values[0]*(scale/20), 
									  (int)event.values[1]*(scale/20),
									  (int)event.values[2]*(scale/20),
									  (int)(System.currentTimeMillis()-startTime)/10);
						  }
						  if (SensorReader.this.sensorID == Sensor.TYPE_ORIENTATION) {
							  sl.setOrientValues(event.values[0], 
									  event.values[1],
									  event.values[2]);
						  }
					  }
			      } else {
			    	  Log.i(tag, "Not an applicable sensor type "+event.sensor.getName());
			      }
		    }

			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// TODO Auto-generated method stub
				
			}
	    };
		
	}
	
	public void registerListener(ISensorListener l) {
		Log.d(tag, "Register listener");
		listeners.add(l);
	}
	
	public boolean removeListener(ISensorListener l) {
		if (listeners.contains(l)) {
			return listeners.remove(l);
		}
		return false;
	}
	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub

	}

	public void start() {
		Log.d(tag, "Start called ");
		sm.registerListener(eventListener, sensor, SensorManager.SENSOR_STATUS_ACCURACY_LOW);
		startTime = System.currentTimeMillis();
	}
	
	public void stop() {
		Log.d(tag, "Stop called ");
		if (eventListener != null) {
			Log.d(tag, "unregister sensor "+eventListener);
			sm.unregisterListener(eventListener);			
		}
	}
}
